package com.test.oauth2;

import com.test.mapper.SysUserMapper;
import com.test.pojo.SysUser;
import com.test.pojo.vo.UserInfoVo;
import com.test.utils.RequestUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder; // 如果需要密码编码器

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            Map<String, String[]> params = RequestUtil.getParameters(RequestUtil.getHttpServletRequest(), true);
            log.info("客户端查询: {}", username);

            // 查询数据库获取用户信息
            SysUser sysUser = sysUserMapper.selectByUsername(username);
            if (sysUser == null || !"0".equals(sysUser.getStatus())) {
                throw new UsernameNotFoundException("用户账号或密码不正确！");
            }

            // 创建并填充用户信息VO
            UserInfoVo userInfoVo = new UserInfoVo();


//            // 手动设置关键字段（防止被覆盖）
//            userInfoVo.setId(sysUser.getId());
//            userInfoVo.setUserName(sysUser.getUserName());
//            userInfoVo.setUserPassword(sysUser.getUserPassword());
            BeanUtils.copyProperties(sysUser, userInfoVo);
            // 设置角色和权限
            userInfoVo.setRoleList(getUserRoles(sysUser.getId()));
            userInfoVo.setPermissionList(getUserPermissions(sysUser.getId()));

            // 检查账户状态
            if (!userInfoVo.isEnabled()) {
                throw new UsernameNotFoundException("用户账号已禁用");
            }
            if (!userInfoVo.isAccountNonExpired()) {
                throw new UsernameNotFoundException("用户账号已过期");
            }
            if (!userInfoVo.isAccountNonLocked()) {
                throw new UsernameNotFoundException("用户账号已被锁定");
            }
            if (!userInfoVo.isCredentialsNonExpired()) {
                throw new UsernameNotFoundException("用户凭证已过期");
            }

            log.info("复制用户: {}", userInfoVo);
            return userInfoVo;
        } catch (Exception e) {
            log.error("加载用户信息时出错", e);
            throw new UsernameNotFoundException(e.getMessage());
        }
    }

    // 示例方法，用于获取用户的角色列表
    private List<String> getUserRoles(String userId) {
        // 这里应该是实际获取角色逻辑，例如从数据库查询
        List<String> authorityList = new ArrayList<>();
        authorityList.add("admin");
        return authorityList;
//        return sysUserMapper.selectRolesByUserId(userId);
    }

    // 示例方法，用于获取用户的权限列表
    private List<String> getUserPermissions(String userId) {
        // 这里应该是实际获取权限逻辑，例如从数据库查询
        List<String> authorityList = new ArrayList<>();
        authorityList.add("admin");
        return authorityList;
//        return sysUserMapper.selectPermissionsByUserId(userId);

    }
}